package com.easysoft.framework;

import com.easysoft.commons.utils.LoginType;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.Map;

public class CustomModularRealmAuthenticator extends ModularRealmAuthenticator {
    private Map<String, Realm> definedRealms;

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        assertRealmsConfigured();
        CustomUsernamePasswordToken token = (CustomUsernamePasswordToken) authenticationToken;

        if (StringUtils.equals(token.getLoginType(), LoginType.SHIRO_ADMIN_LOGIN)) {
            return doSingleRealmAuthentication(definedRealms.get(LoginType.SHIRO_ADMIN_LOGIN), token);
        }
        if (StringUtils.equals(token.getLoginType(), LoginType.SHIRO_USERS_LOGIN)) {
            return doSingleRealmAuthentication(definedRealms.get(LoginType.SHIRO_USERS_LOGIN), token);
        }
        return null;
    }

    public void setDefinedRealms(Map<String, Realm> definedRealms) {
        this.definedRealms = definedRealms;
    }
}
